//
//  EmoticonKeyboardView.swift
//  EmojiKeyboard
//
//  Created by ZhangZiang on 15/12/27.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit

private let toolBarHeight : CGFloat = 35
private let collectionCellID = "EmojiCollectionCellID"

class EmoticonKeyboardView: UIView {

    private lazy var packages = EmoticonManager().packages
    
    //定义事件的回调(相当于代理)
    var selectEmoticonBlock : ((em : Emoticon) -> ())?
    
    // toolBar的点击方法
    @objc private func itemDidClicked(item : UIBarButtonItem) {
    
        let index = NSIndexPath(forItem: 0, inSection: item.tag)
        
        collectionView.scrollToItemAtIndexPath(index, atScrollPosition: .Left, animated: true)
    }
    
    init(selectEmoticonBlock : (em : Emoticon) -> ()) {
        //重写init方法,初始化回调block
        self.selectEmoticonBlock = selectEmoticonBlock
        
        let rect = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 220)
        
        super.init(frame: rect)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
       
        
        addSubview(toolBar)
        addSubview(collectionView)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(self)
            make.height.equalTo(toolBarHeight)
        }
        
        collectionView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(toolBar.snp_top)
            make.left.right.top.equalTo(self)
        }
        
        setupToolBar()
    }
    
    private func setupToolBar() {
        
        var items = [UIBarButtonItem]()
        
        var index = 0
        for p in packages {
            let item = UIBarButtonItem(title: p.group_name_cn, style: .Plain, target: self, action: "itemDidClicked:")
            item.tag = index
            index++
            
            items.append(item)
            
            let bounce = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(bounce)
        }
        
        items.removeLast()
        
        toolBar.items = items
    }
    
    private lazy var toolBar = UIToolbar()
    
    private lazy var collectionView : UICollectionView = {
        //设置流水布局
        let layout = UICollectionViewFlowLayout()
        
        let itemW = UIScreen.mainScreen().bounds.width/7
        
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        layout.scrollDirection = .Horizontal
        //调整sectionInset(否则会有黑色间隔)
        let margin = (self.bounds.height - toolBarHeight - 3*itemW)/4
        
        layout.sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        
        //实例化collectionView
        let collectionV = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        
        //注册cell
        collectionV.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: collectionCellID)
        
        collectionV.delegate = self
        collectionV.dataSource = self
        
        collectionV.pagingEnabled = true
        collectionV.backgroundColor = UIColor.whiteColor()
        return collectionV
    }()

}

extension EmoticonKeyboardView : UICollectionViewDelegate, UICollectionViewDataSource {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }

    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticon.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionCellID, forIndexPath: indexPath) as! EmoticonCell
        
        cell.emoticon = packages[indexPath.section].emoticon[indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let em = self.packages[indexPath.section].emoticon[indexPath.item]
        
        //执行闭包
        selectEmoticonBlock?(em: em)
    }
}

class EmoticonCell: UICollectionViewCell {
    
    var emoticon : Emoticon? {
        didSet {
            emoticonBtn.setImage(UIImage(contentsOfFile: emoticon?.imagePath ?? ""), forState: .Normal)
            //emoji字符串
            emoticonBtn.setTitle(emoticon?.emojiStr ?? "", forState: .Normal)
            
            if let em = emoticon where em.isDelete == true {
                emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(emoticonBtn)
//         contentView.backgroundColor = UIColor.whiteColor()
        emoticonBtn.backgroundColor = UIColor.whiteColor()
        emoticonBtn.frame = CGRectInset(bounds, 4, 4)//有内边距的
        
//        emoticonBtn.frame = contentView.bounds
        //调整emoji表情的大小(本质上就是字符串)
        emoticonBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        //只通过cell的代理方法点击
        emoticonBtn.userInteractionEnabled = false
    }
    //用btn可以同时设置文字和图片
    private lazy var emoticonBtn = UIButton()
}
